package com.train.mgr.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.train.common.exception.BusinessException;
import com.train.common.model.PageResult;
import com.train.common.utils.AuthUtils;
import com.train.common.utils.StringUtils;
import com.train.mgr.modules.system.dto.request.PositionAddReqDTO;
import com.train.mgr.modules.system.dto.request.PositionImportDTO;
import com.train.mgr.modules.system.dto.request.PositionReqDTO;
import com.train.mgr.modules.system.dto.request.PostWeightDTO;
import com.train.mgr.modules.system.dto.response.PositionDetailRespDTO;
import com.train.mgr.modules.system.dto.response.PostWeightProjDTO;
import com.train.mgr.modules.system.entity.Position;
import com.train.mgr.modules.system.mapper.PositionMapper;
import com.train.mgr.modules.system.service.IPositionService;
import com.train.mgr.modules.system.service.IPostWeightService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 岗位信息 服务层处理
 *
 * @author cxg
 */
@Slf4j
@Service("positionService")
public class PositionServiceImpl implements IPositionService {

    @Autowired
    private PositionMapper postMapper;

    @Autowired
    private IPostWeightService postWeightService;

    /**
     * 分页查询列表
     * @param params
     * @return
     */
    @Override
    public PageResult<Position> pageList(PositionReqDTO params){
        params.setCustomerId(AuthUtils.getCurrentUser().getCustomerId());
        Page<PositionReqDTO> page = params.buildPage();
        Page<Position> resultPage = postMapper.selectPostList(page,params);
        return PageResult.of(resultPage, Position.class);
    }

    /**
     * 查询所有岗位
     *
     * @return 岗位列表
     */
    @Override
    public List<Position> selectPostAll() {
        return postMapper.selectPostAll();
    }

    /**
     * 通过岗位ID查询岗位信息
     *
     * @param postId 岗位ID
     * @return 角色对象信息
     */
    @Override
    public Position selectPostById(Long postId){
        Position position = postMapper.selectPostById(postId);
        if(StringUtils.isNull(position)){
            throw new BusinessException("记录不存在～");
        }
        return position;
    }
    /**
     * 通过岗位ID查询岗位信息
     * @param postId 岗位ID
     * @return 角色对象信息
     */
    @Override
    public PositionDetailRespDTO findDetailById(Long postId) {
        PositionDetailRespDTO respBean = new PositionDetailRespDTO();
        Position position = postMapper.selectPostById(postId);
        if(StringUtils.isNull(position)){
            throw new BusinessException("记录不存在～");
        }

        respBean.setPostCode(position.getPostCode());
        respBean.setPostId(position.getPostId());
        respBean.setPostName(position.getPostName());

        List<PostWeightDTO> postWeightRespList = new ArrayList<PostWeightDTO>();
        List<PostWeightProjDTO> list = postWeightService.selectGroupByCateId(position.getCustomerId(),position.getPostId());
        if(CollectionUtil.isNotEmpty(list)){
            for(PostWeightProjDTO bean : list){
                PostWeightDTO dto = new PostWeightDTO();
                dto.setCategoryId(bean.getCategoryId());
                dto.setWeightType(bean.getWeightType());

                String[] projectIdArray = bean.getProjectId().split(",");
                dto.setProjectIdList(stringArrayToLongList(projectIdArray));
                postWeightRespList.add(dto);
            }
        }
        respBean.setPostWeight(postWeightRespList);

        return respBean ;
    }

    public static List<Long> stringArrayToLongList(String[] array) {
        List<Long> list = new ArrayList<>();
        for (String str : array) {
            try {
                list.add(Convert.toLong(str, 0L)); // 将字符串转换为Long，第二个参数是转换失败时的默认值
            } catch (Exception e) {
                // 处理转换异常，例如打印错误信息或忽略该元素
                System.err.println("无法将 '" + str + "' 转换为Long: " + e.getMessage());
            }
        }
        return list;
    }

    /**
     * 根据用户ID获取岗位选择框列表
     *
     * @param userId 用户ID
     * @return 选中岗位ID列表
     */
    @Override
    public List<Long> selectPostListByUserId(Long userId)
    {
        return postMapper.selectPostListByUserId(userId);
    }

    /**
     * 校验岗位名称是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public boolean checkPostNameUnique(PositionAddReqDTO post) {
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
        Position info = postMapper.checkPostNameUnique(post.getPostName(),customerId);
        if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) {
            return false;
        }
        return true;
    }

    @Override
    public Position findPostByName(String postName,Long customerId){
        Position info = postMapper.checkPostNameUnique(postName,customerId);
        if (StringUtils.isNull(info)) {
            throw new BusinessException("岗位名称数据为空");
        }
        return info;
    }

    @Override
    public boolean isExistPostName(String postName,Long customerId){
        Position info = postMapper.checkPostNameUnique(postName,customerId);
        if (StringUtils.isNotNull(info)) {
            return true;
        }
        return false;
    }

    /**
     * 校验岗位编码是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public boolean checkPostCodeUnique(PositionAddReqDTO post) {
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
        Position info = postMapper.checkPostCodeUnique(post.getPostCode(),customerId);
        if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) {
            return false;
        }
        return true;
    }


    /**
     * 删除岗位信息
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public int deletePostById(Long postId) {
        return postMapper.deletePostById(postId);
    }

    /**
     * 批量删除岗位信息
     *
     * @param postIds 需要删除的岗位ID
     * @return 结果
     */
    @Override
    public int deletePostByIds(Long[] postIds) {
  //      for (Long postId : postIds) {
 //           Position post = selectPostById(postId);
//            if (countUserPostById(postId) > 0) {
//                throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName()));
//            }
 //       }
        return postMapper.deletePostByIds(postIds);
    }

    /**
     * 新增保存岗位信息
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean insertPost(PositionAddReqDTO post) {
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        Position bean = new Position();
        bean.setCustomerId(AuthUtils.getCurrentUser().getCustomerId());
        bean.setCreateBy(AuthUtils.getCurrentUser().getNickName());
        bean.setPostCode(post.getPostCode());
        bean.setPostName(post.getPostName());
        postMapper.insert(bean);
        //保存岗位关联的职位
        postWeightService.saveOrUpdatePostWeight(bean.getPostId(),customerId,post.getPostWeight());
        return true;
    }

    /**
     * 修改保存岗位信息
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePost(PositionAddReqDTO post) {
        Position bean = postMapper.selectById(post.getPostId());
        bean.setPostCode(post.getPostCode());
        bean.setPostName(post.getPostName());
        bean.setPostId(post.getPostId());
        bean.setUpdateBy(AuthUtils.getCurrentUser().getNickName());
        bean.setUpdateTime(new Date());
        postWeightService.saveOrUpdatePostWeight(bean.getPostId(),bean.getCustomerId(),post.getPostWeight());
        return postMapper.updateById(bean);
    }

    @Override
    @Transactional
    public boolean saveExcelData(List<PositionImportDTO> positionList){
       // log.info("saveExcelData:{}",positionList.toString());
        //导入数据的excel格式数据处理
        this.checkListData(positionList);

        for(PositionImportDTO dto : positionList){
            Position bean = new Position();
            bean.setPostName(dto.getPostName());
            bean.setPostCode(dto.getPostCode());
            bean.setCustomerId(AuthUtils.getCurrentUser().getCustomerId());
            bean.setCreateBy(AuthUtils.getUsername());
            bean.setCreateTime(new Date());
            postMapper.insert(bean);
        }
        return true;
    }

    private void checkListData(List<PositionImportDTO> positionList){
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        if(CollectionUtil.isEmpty(positionList)){
            throw new BusinessException("导入数据为空");
        }
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<positionList.size();i++){
            PositionImportDTO position = positionList.get(i);
            String line = "第【"+(i+1)+"】行，";
            if(StringUtils.isEmpty(position.getPostCode())){
                sb.append(line + "【岗位代码是空值】；");
            }
            if(StringUtils.isEmpty(position.getPostName())){
                sb.append(line + "【岗位名称是空值】；");
            }
            Position codeBean = postMapper.checkPostCodeUnique(position.getPostCode(),customerId);
            if(StringUtils.isNotNull(codeBean)){
                sb.append(line + "【岗位代码["+codeBean.getPostCode()+"]重复】；");
            }
            Position nameBean = postMapper.checkPostNameUnique(position.getPostName(),customerId);
            if(StringUtils.isNotNull(nameBean)){
                sb.append(line + "【岗位名称["+nameBean.getPostCode()+"]重复】；");
            }

            if(StringUtils.isNotBlank(sb)){
                throw new BusinessException(sb.toString());
            }
        }
    }
}
